package com.gitee.maskit.web;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.ZoneId;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.function.Function;

/**
 * @author z0228
 */
@Slf4j
public class WebFilter implements Filter {
    public static final String NAME = "MaskitWebFilter";
    private static final int GMT_OFFSET = TimeZone.getDefault().getRawOffset();
    private static final Function<Long, Date> GMT = time -> new Date(time - GMT_OFFSET);
    private static final String HEADER_X_FORWARDED_FOR = "X-Forwarded-For";
    private static final String HEADER_REMOTE_IP = "RemoteIp";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final long startAt = System.currentTimeMillis();

        WebHolder.REQUEST.set(servletRequest);
        WebHolder.RESPONSE.set(servletResponse);

        WebHolder.LOCALE.set(servletRequest.getLocale());

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            if (log.isDebugEnabled() && servletRequest instanceof HttpServletRequest) {
                final String ip;
                HttpServletRequest hsr = (HttpServletRequest) servletRequest;
                if (null != hsr.getHeader(HEADER_X_FORWARDED_FOR)) {
                    ip = hsr.getHeader(HEADER_X_FORWARDED_FOR);
                } else if (null != hsr.getHeader(HEADER_REMOTE_IP)) {
                    ip = hsr.getHeader(HEADER_REMOTE_IP);
                } else if (null != hsr.getRemoteHost()) {
                    ip = hsr.getRemoteHost();
                } else {
                    ip = hsr.getRemoteAddr();
                }
                log.debug("Handled request [{}] from [{}] in [{}]ms from GMT [{}]",
                    hsr.getRequestURI(),
                    ip,
                    System.currentTimeMillis() - startAt,
                    GMT.apply(startAt));
            }
        }
    }

    @Override
    public void destroy() {
        WebHolder.clearAll();
    }
}
